/*
 * @lc app=leetcode.cn id=443 lang=cpp
 *
 * [443] 压缩字符串
 */
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <vector>
#include <string>
#include <cmath>

using namespace std;
// @lc code=start
class Solution {
public:
    int compress(vector<char>& chars) {
        //双指针
        int n = chars.size();
        int write = 0, left = 0;
        for (int read = 0; read < n; read++) {
            //读到不一样的字符或最后一个字符
            if (read == n - 1 || chars[read] != chars[read + 1]) {
                chars[write] = chars[read];
                write++;
                int num = read - left + 1;
                //将num转成字符串写入，并翻转
                if (num > 1) {
                    int anchor = write;
                    while (num > 0) {
                        chars[write] = num % 10 + '0';
                        write++;
                        num /= 10;
                    }
                    reverse(&chars[anchor], &chars[write]);
                }
                left = read + 1;
            }
        }
        return write;
    }
};
// @lc code=end

